package myky.com.doctorapp.ui
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import com.foamtrace.photopicker.ImageCaptureManager
import com.foamtrace.photopicker.PhotoPickerActivity
import com.google.gson.Gson

import com.gyf.barlibrary.ImmersionBar
import kotlinx.android.synthetic.main.activity_remote_details.*
import kotlinx.android.synthetic.main.public_common_title.*

import myky.com.doctorapp.R
import myky.com.doctorapp.adapter.ImageAdapter
import myky.com.doctorapp.adapter.RemoteStatusAdapter
import myky.com.doctorapp.base.BaseActivity
import myky.com.doctorapp.contract.ImageUploadContract
import myky.com.doctorapp.contract.RemoteDetailsActivityContract
import myky.com.doctorapp.entity.*
import myky.com.doctorapp.presenter.RemoteDetailsActivityPresenter
import myky.com.doctorapp.utils.AddPhotoUtils
import myky.com.doctorapp.utils.Constants
import myky.com.doctorapp.utils.ImageUtils
import myky.com.doctorapp.utils.UriUtils
import myky.com.doctorapp.wight.SelfDialog
import java.util.*
import kotlin.collections.ArrayList

/**
 * Description: 远程详情
 * @author wuyang
 * Created by 2019/3/11 11:25
 */
class RemoteDetailsActivity : BaseActivity<RemoteDetailsActivityPresenter,RemoteDetailsEntity.PayLoadBean>(),RemoteDetailsActivityContract.View,View.OnClickListener, ImageUploadContract {



    lateinit var remoteId :String
    lateinit var imagelist:MutableList<ImageEntity>
    lateinit var imageUploadlist:MutableList<ImageEntity>
    lateinit var imagelistAll:ArrayList<ImageEntity>
    lateinit var imageAdapter:ImageAdapter
    lateinit var remotelogsAdapter:RemoteStatusAdapter
    // 相机拍照处理类
    var captureManager: ImageCaptureManager? = null
    lateinit var remotelogList:MutableList<RemoteDetailsEntity.PayLoadBean.DetailBean.RemoteLogsBean>
    private val OPEN :String = "展开"
    private val CLOSE :String = "收起"
    var appStatus:Int=0
    lateinit var healthRecordEntity: HealthRecordEntity.PerProfileBean
    override fun getPresenter(): RemoteDetailsActivityPresenter = RemoteDetailsActivityPresenter()
    override fun reloadActivity() {
    }

    override fun injectTarget(): View =findViewById(R.id.new_remote_detail_layout)

    override fun initData() {
        remoteId=intent.getStringExtra(Constants.REMOTEID)
        mPresenter.premoteDetail(remoteId)
    }

    override fun initView() {
        ImmersionBar.with(this)
                .statusBarColor(R.color.colorPrimary)
                .titleBar(R.id.remote_detail_title)
                .init()
        conmonTitleTextView.text = getText(R.string.success_details)
        imagelist=ArrayList()
        imagelistAll=ArrayList()
        remotelogList=ArrayList()
        imageUploadlist=ArrayList()
        imageAdapter= ImageAdapter(imagelist)
        captureManager = ImageCaptureManager(this)
        remotelogsAdapter= RemoteStatusAdapter(remotelogList)
        new_remote_detail_recycler_case.layoutManager = GridLayoutManager(this, 3)
        new_remote_detail_recycler_status.layoutManager = LinearLayoutManager(this)
        new_remote_detail_recycler_case.adapter=imageAdapter
        new_remote_detail_recycler_status.adapter=remotelogsAdapter
        new_remote_detail_btn.setOnClickListener(this)
        new_remote_detail_cancel_tv.setOnClickListener(this)
        new_remote_detail_buchong_tv.setOnClickListener(this)
        new_remote_detail_more_img.setOnClickListener(this)
        new_remote_detail_health.setOnClickListener(this)
        backLayout.setOnClickListener(this)


    }

    override fun getContenView(): Int=R.layout.activity_remote_details

    /**
     * 远程补充资料
     */
    override fun suppltyResult(remoteBean: RemoteRepeatEntity.PayLoadBean) {
        hideLoading()
        showShortToast(getString(R.string.remote_supply_success))
        imagelistAll.clear()
        imagelist.clear()
        remotelogList.clear()
        mPresenter.premoteDetail(remoteId)
    }

    /**
     * 取消远程结果
     */
    override fun cancelResult(remoteBean: RemoteRepeatEntity.PayLoadBean) {
        hideLoading()
        showShortToast(getString(R.string.remote_cancel_success))
        imagelistAll.clear()
        imagelist.clear()
        remotelogList.clear()
        mPresenter.premoteDetail(remoteId)
    }
    /**
     * 远程详情结果
     */
    override fun showDataSuccess(datas: RemoteDetailsEntity.PayLoadBean) {

        var detail = datas.detail
        //健康档案快照
        if(detail.remoteHealthSnapshot!=null){
            var s = detail.remoteHealthSnapshot.json.replace("\\", "")
            var gson= Gson()
        healthRecordEntity=gson.fromJson(s,HealthRecordEntity.PerProfileBean::class.java)
        }
        new_remote_detail_nickName.text=detail.remoteDisease.caseTemplateName
        new_remote_detail_visits.text=resources.getStringArray(R.array.remote_freq)[detail.freq]
        new_remote_detail_isknow.text=resources.getStringArray(R.array.remote_known)[detail.known]
        new_remote_detail_content_simple.text=detail.description
        new_remote_detail_content.text=detail.description
        new_remote_detail_doctor_iv.setImageURI(UriUtils.getUriInstance().getUri(detail.doctor.headPhoto))
        new_remote_detail_doctor_tv.text=detail.doctor.realname
        new_remote_detail_remark.text=detail.remark
        appStatus=detail.currStatus
        //不同状态时隐藏和显示btn
        if (appStatus == 1 || appStatus == 0) {
            new_remote_detail_cancel_tv.text=getString(R.string.remote_status_cancels)
            new_remote_detail_cancel.visibility=View.VISIBLE
        } else if (appStatus == 5) {
            new_remote_detail_cancel_tv.visibility=View.GONE
            new_remote_detail_cancel.visibility=View.VISIBLE
        }else{
            new_remote_detail_cancel.visibility=View.GONE
        }
        //图片病历集合
        var pictures = detail.remotePictures
        if (pictures!=null) {
            for (picture in pictures) {
                var imageEntity: ImageEntity = ImageEntity()
                imageEntity.illnessName = picture.caseTemplateName
                imageEntity.path = picture.pictureMD5
                imagelistAll.add(imageEntity)
            }
            if (imagelistAll.size>3){
                imagelist.addAll(imagelistAll.subList(0,3))
            }else{
                imagelist.addAll(imagelistAll)
            }
                imageAdapter.notifyDataSetChanged()
        }

        //问诊状态集合
        var remoteLogs = detail.remoteLogs
        remotelogList.add(RemoteDetailsEntity.PayLoadBean.DetailBean.RemoteLogsBean(detail.createtime))
        var remoteLogsBean:RemoteDetailsEntity.PayLoadBean.DetailBean.RemoteLogsBean= RemoteDetailsEntity.PayLoadBean.DetailBean.RemoteLogsBean()
        if (appStatus==1){
            remoteLogsBean.currStatusText=getString(R.string.remote_status_t)
            remotelogList.add(remoteLogsBean)
        }
        if (appStatus==5){
            //患者需要补充资料时去掉下一步操作
            new_remote_detail_remark.setTextColor(Color.parseColor("#ff0000"))
            remoteLogs.remove(remoteLogs[remoteLogs.size - 1])
        }
        //患者已补充资料时去掉5患者需要补充资料状态
        if (appStatus > 5) {
            for (i in remoteLogs.indices) {
                if (remoteLogs[i].currStatus === 5) {
                    remoteLogs.removeAt(i)
                }
            }
        }
        if (appStatus == 9) {
            for (i in remoteLogs.indices) {
                if (remoteLogs[i].currStatus === 9) {
                    if (remoteLogs[i].cause !== 5) {
                        remoteLogs.removeAt(i)
                    }
                }
            }
        }
        //去掉默认为1的待接诊状态
        remoteLogs.removeAt(0)
        remotelogList.addAll(remoteLogs)
        remotelogList.reverse()
        remotelogsAdapter.notifyDataSetChanged()
    }

    override fun onClick(view: View) {

        when(view.id){
            R.id.backLayout->finish()
            R.id.new_remote_detail_btn->
            {
                var text = new_remote_detail_btn.text
                if (text==OPEN){
                    new_remote_detail_btn.text=CLOSE
                    new_remote_detail_content_layout.visibility=View.VISIBLE
                    new_remote_detail_content_simple.visibility=View.GONE
                }
                if (text==CLOSE){
                    new_remote_detail_btn.text=OPEN
                    new_remote_detail_content_layout.visibility=View.GONE
                    new_remote_detail_content_simple.visibility=View.VISIBLE
                }
            }
            R.id.new_remote_detail_cancel_tv->{
                val selfDialog = SelfDialog(this)
                selfDialog.setTitle(getString(R.string.remote_cancel_dialog))
                selfDialog.setYesOnclickListener(getString(R.string.set_time_dialog_btn_qx), SelfDialog.onYesOnclickListener {
                    mPresenter.pcancelResult(remoteId)
                    selfDialog.dismiss()
                })
                selfDialog.setNoOnclickListener(getString(R.string.set_time_dialog_btn_qd)) {
                    selfDialog.dismiss()
                }
                selfDialog.show()

            }
            R.id.new_remote_detail_more_img->{
               var bundle=Bundle()
                bundle.putSerializable(Constants.IMAGELIST,imagelistAll)
                startActivity(ImageListActivity::class.java,bundle)

            }
            R.id.new_remote_detail_health->{
                var bundle=Bundle()
                bundle.putSerializable(Constants.HEALTHELIST,healthRecordEntity)
                startActivity(HealthRecordActivity::class.java,bundle)
            }
            R.id.new_remote_detail_buchong_tv->
            {
                //限制一次最大上传9张图片
                var size = imagelistAll.size
                var limit=18-size
                if(limit>9){
                    limit=9
                }else if(limit==0){
                    showShortToast(getString(R.string.remote_supply_limit))
                    return
                }

                AddPhotoUtils.getPhotos(this, 31, 0, limit, ArrayList<String>(), 1)
            }
        }
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data != null && resultCode == RESULT_OK) {
            when (requestCode) {

                Constants.CASE_MEDICALRECORD -> {
//                    imagelist.clear()
//                    imagelist.addAll(StringFileUtils.getImgList())
//                    val deletePath = data.getStringExtra("deletePath")
//                    cameraList.remove(deletePath)
//                    val strings = java.util.ArrayList<String>()
//                    for (x in 0 until imagelist.size - 1) {
//                        strings.add(imagelist.get(x).getPath())
//                    }
                }
                Constants.TAKE_CAMERA -> {

                    val path = data.getStringExtra(Constants.IMAGEPATH)
                    //扫描及时更新新相册
                    captureManager?.galleryAddPic(path)
                    imageUploadlist.add(ImageEntity(path))
//                    val intent = Intent(context, AddTime_MedicalRecordActivity::class.java)
//                    intent.putExtra("photoLists", takePhotos)
//                    intent.putExtra("FROM_TYPE", Constants.NEW_BESPEAK_TYPE)
//                    intent.putExtra("OPERATION_TYPE", ADDTIME_RESULTCODE)
//                    startActivityForResult(intent, ADDTIME_RESULTCODE)
                }

                Constants.TAKE_ALBUM -> {
                    if (data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT) != null) {
                        val data1 = data.data

                       var imagePathsResult = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT)
                        for (s in imagePathsResult) {
                            imageUploadlist.add(ImageEntity(s))
                        }

//                        val intent = Intent(context, AddTime_MedicalRecordActivity::class.java)
//                        intent.putExtra("photoLists", imagePathsResult)
//                        intent.putExtra("FROM_TYPE", Constants.NEW_BESPEAK_TYPE)
//                        intent.putExtra("OPERATION_TYPE", ADDTIME_RESULTCODE)
//                        startActivityForResult(intent, ADDTIME_RESULTCODE)
                    }
                }
            }
            if (imageUploadlist.size>0){
                ImageUtils.upload(this,imageUploadlist,this)
            }
        }

    }

    /**
     * 图片上传成功
     */
    override fun uploadSuccess(result: MutableList<String>) {
        var imageList:MutableList<RemoteSupplyEntity.RemotePhotosBean>
        imageList=ArrayList()
        if(result!=null){
            for (s in result) {
                var bean=RemoteSupplyEntity.RemotePhotosBean()
                bean.checkDate="2019-02-11"
                bean.pictureMD5=s
                imageList.add(bean)
            }
        }
        var remoteSupplyEntity=RemoteSupplyEntity()
        remoteSupplyEntity.remotePhotos=imageList
        remoteSupplyEntity.version="v2.0"
        mPresenter.premoteSupply(remoteId,remoteSupplyEntity)
    }

    override fun uploadFail(msg: String?) {
        hideLoading()
        showShortToast(msg)
    }
}
